package websphinx;

import java.util.Vector;

/**
 * look up the child of parent if it has the given tag (ptr). yes return tag, no
 * return null;
 * 
 * @author Administrator
 * 
 */
public class MatchChildTag implements MatchAction {

	private String tagName = null;
	private Vector attributes = null;

	public MatchChildTag(String name, Vector attributes) {
		this.tagName = name.toLowerCase();
		this.attributes = attributes;
	}

	@Override
	/**
	 * input the element that starts to search, 
	 * return the result element if search success, others return null 
	 */
	public boolean match(Matcher matcher) {
		Element father = matcher.context.getCurPointer();
		if (matcher.next != null && matcher.next.getParent() != null
				&& !matcher.next.getParent().equals(father))
			return false;

		Element child = matcher.next;

		if (child != null) {
			do {
				if (compare(child)) {
					matcher.next = child.getChild();
					matcher.context.addPointer(child);
					return true;
				}
			} while ((child = child.getSibling()) != null);
		}

		return false;

	}

	private boolean compare(Element tag) {
		if (tag.isText())
			return false; // match text returns false;
		boolean eq = tag.getTagName().toLowerCase().equals(this.tagName);

		if (!eq)
			return eq;
		else {
			String value = null;
			for (int i = 0; i < attributes.size(); i += 2) {
				value = tag.getHTMLAttribute((String) attributes.get(i));
				if (value == null)
					return false;
				else if (!value.equals(attributes.get(i + 1)))
					return false;
			}
			return true;
		}
	}

	@Override
	public boolean apply(Matcher matcher) {
		matcher.applyResult.append('<');
		matcher.applyResult.append(this.tagName);
		if (attributes != null && attributes.size() != 0) {
			for (int i = 0; i < attributes.size(); i += 2) {
				matcher.applyResult.append(' ');
				matcher.applyResult.append(attributes.elementAt(i));
				matcher.applyResult.append('=');
				matcher.applyResult.append(attributes.elementAt(i + 1));
			}
		}
		matcher.applyResult.append('>');

		return true;
	}

}
